package com.katesoft.scale4j.agent;

import static java.util.Arrays.asList;
import static org.perf4j.helpers.MiscUtils.splitAndTrim;

import java.util.Collection;
import java.util.LinkedHashSet;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.log.Logger;

/**
 * This class allows you to start application service from spring configuration files.
 * <p/>
 * Programs arguments threat as spring configuration files locations(also each parameter can be
 * container of few location separated by comma).
 * 
 * @author kate2007
 */
public final class SpringConfigurationRunner {
   private static final Logger LOGGER = LogFactory.getLogger(SpringConfigurationRunner.class);

   public static void main(String[] args) {
      Collection<String> locations = new LinkedHashSet<String>();
      for (String arg : args) {
         locations.addAll(asList(splitAndTrim(arg, ",")));
      }
      LOGGER.info("starting jvm using spring launcher with locations = %s", locations.toString());
      try {
         ClassPathXmlApplicationContext c = new ClassPathXmlApplicationContext(
                  locations.toArray(new String[locations.size()]));
         c.registerShutdownHook();
         c.addApplicationListener(new ApplicationListener<ApplicationEvent>() {
            @Override
            public void onApplicationEvent(ApplicationEvent event) {
               if (event instanceof ContextClosedEvent) {
                  LOGGER.info("spring application context %s get closed",
                           ((ContextClosedEvent) event).getApplicationContext().getDisplayName());
                  Thread.currentThread().interrupt();
               }
            }
         });
      } catch (Exception e) {
         LOGGER.error(e);
      }
   }

   private SpringConfigurationRunner() {
   }
}
